<template>
	<view class="page-main">
		<CustomNavBar :title="option.title"></CustomNavBar>
		<view class="page-main-head">
			<view class="unit-body" v-if="detail">
				<image :src="detail.photoUrl ? detail.photoUrl : '/static/logo.png'" class="" />
				<view class="list-item">
					<text class="color-999">{{detail.name}}</text>
					<view class="list-con">
						<view class="list-tag">
							<text class="list-tag-label">设备类型：</text>
							<text class="list-tag-value">{{detail.deviceType.text}}</text>
						</view>
						<view class="list-tag">
							<text class="list-tag-label">ID：</text>
							<text class="list-tag-value">{{detail.id}}</text>
						</view>
						<view class="list-tag">
							<text class="list-tag-label">产品名称：</text>
							<text class="list-tag-value">{{detail.productName}}</text>
						</view>
					</view>
				</view>
				<view :class="detail.state.value === 'online' ? 'list-status' : 'list-status list-status-red'">
					<i></i>
					<text>{{detail.state.text}}</text>
				</view>
			</view>
		</view>
		<view class="page-detail">
			<view class="page-tabs">
				<view :class="active === 0 ? 'page-tab page-tab-cur' : 'page-tab'" @click="changeTab(0)">实例信息</view>
				<view :class="active === 1 ? 'page-tab page-tab-cur' : 'page-tab'" @click="changeTab(1)">运行状态</view>
				<view :class="active === 2 ? 'page-tab page-tab-cur' : 'page-tab'" @click="changeTab(2)">设备功能</view>
			</view>
			<scroll-view class="page-tab-con" :scroll-y="true">
				<view class="page-info" v-if="active === 0 && detail">
					<view class="page-info-device">
						<view class="page-info-title"><i></i>设备信息</view>
						<view class="page-info-device-con">
							<view class="page-info-item">
								<text class="page-info-label">设备ID：</text>
								<text class="page-info-value">{{detail.id || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">产品名称：</text>
								<text class="page-info-value">{{detail.productName || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">设备类型：</text>
								<text class="page-info-value">{{detail.deviceType.text || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">连接协议：</text>
								<text class="page-info-value">{{detail.transport || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">消息协议：</text>
								<text class="page-info-value">{{detail.protocolName || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">创建时间：</text>
								<text class="page-info-value">{{detail.createTime || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">注册时间：</text>
								<text class="page-info-value">{{detail.registerTime || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">最后上线时间：</text>
								<text class="page-info-value">{{detail.onlineTime || '--'}}</text>
							</view>
							<view class="page-info-item">
								<text class="page-info-label">说明：</text>
								<text class="page-info-value">{{detail.description || '--'}}</text>
							</view>
						</view>
					</view>
					<view class="page-info-config">
						<view class="page-info-title"><i></i>配置</view>
						<view class="page-info-config-con" v-for="(item,i) in config" :key="i">
							<view class="page-info-config-title">{{item.name}}</view>
							<view class="page-info-item" v-for="(child,c) in item.properties" :key="c">
								<text class="page-info-label">{{child.name}}：</text>
								<text class="page-info-value">{{detail.configuration[child.name] || '--'}}</text>
								<uni-icons v-if="child.type.type === 'password'" :type="isShow ? 'eye-slash' : 'eye'" size="20" @click="changeShow(child)"></uni-icons>
							</view>
						</view>
					</view>
				</view>
				<view class="page-status" v-if="active === 1">
					<view class="page-status-item" v-for="(item,i) in statusList" :key="i">
						<view class="page-status-label">{{item.name}}</view>
						<view class="page-status-value">{{(item.formatValue || item.formatValue === 0) ? Number(item.formatValue).toFixed(2)  : '--'}}{{item.unit || ''}}</view>
						<view class="page-status-label">更新时间</view>
						<view class="page-status-time">{{item.time || '--'}}</view>
					</view>
				</view>
				<view class="page-function" v-if="active === 2">
					<view class="page-function-item" v-for="(item,i) in functionList" :key="i">
						<uni-forms label-position="top" :ref="'baseForm' + i" :modelValue="item">
							<view class="page-function-con" v-for="(child,c) in item.inputs" :key="c">
								<view class="page-function-label">参数名称</view>
								<view class="page-function-value">{{child.name || '--'}}</view>
								<view class="page-function-label">输入类型</view>
								<view class="page-function-value">{{child.valueType.type || '--'}}</view>
								<!-- <view class="page-function-label">值</view> -->
								<uni-forms-item label="值" :name="['inputs',c,child.id]" :required="child.expands.required" :rules="child.expands.required ? [{required: true,errorMessage: '请输入值'}] : []">
									<picker v-if="child.valueType.type === 'enum'" mode="selector" @change="(e) => bindPickerChange(e,child.valueType.elements,i,c,child.id)" :value="selectIndex" :range="child.valueType.elements.map((v) => {return v.text})">
										<view class="uni-input">{{child.valueType.elements.map((v) => {return v.text})[selectIndex]}}</view>
									</picker>
									<uni-easyinput v-else v-model="item.inputs[c][child.id]" placeholder="请输入值" />
								</uni-forms-item>
							</view>
						</uni-forms>
						<view class="page-function-btns" v-if="item.inputs && item.inputs.length > 0">
							<button size="mini" type="primary" @click="submit(i)">执行</button>
							<button size="mini" @click="clearForm(item)">清空</button>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import CustomNavBar from "@/components/customNavBar.vue"
	import _g from '@/static/js/global.js'
	import moment from 'moment'
	moment.locale('zh-cn')
	export default {
		components:{CustomNavBar},
		data() {
			return {
				option:{
					id:'',
					title:''
				},
				detail:null,
				config:[],
				active:0,
				isShow:false,
				properties:[],
				statusList:[],
				functionList:[],
				ws:null,
				timeoutObj:null,
				serveTime:null,
				socketOpen:false,
				selectIndex:0
			}
		},
		onLoad: function(option) {
			this.option = option
			this.getDetail()
			//模拟登录失效
			// setTimeout(() => {
			// 	const appInstance = getApp();
			// 	appInstance.globalData.token = '';
			// }, 3000)
			
		},
		methods: {
			bindPickerChange: function(e,arr,index1,index2,id) {
					this.selectIndex = e.detail.value
					this.functionList[index1].inputs[index2][id] = arr[this.selectIndex].value
			},
			changeTab(val){
				this.active = val
				// if(val === 1){
				// 	this.getStatus()
				// }
			},
			changeShow(data){
				this.isShow = !this.isShow
				if(this.isShow){
					this.detail.configuration[data.name] = this.detail.configuration[data.name + 'Val']
				} else {
					this.detail.configuration[data.name] = '*'.repeat(this.detail.configuration[data.name].length)
				}
			},
			getDetail(){
				const that = this
				const appInstance = getApp();
				_g.apiPost(appInstance.globalData.url + '/api/device-instance/' + that.option.id + '/detail',{},'GET').then(res => {
					if(res.status == 200){
						res.result.createTime = moment(res.result.createTime).format('YYYY-MM-DD HH:mm:ss')
						res.result.registerTime = moment(res.result.registerTime).format('YYYY-MM-DD HH:mm:ss')
						res.result.onlineTime = moment(res.result.onlineTime).format('YYYY-MM-DD HH:mm:ss')
						that.properties = []
						if(res.result.metadata){
							let obj = JSON.parse(res.result.metadata)
							if(obj.functions){
								for(let item of obj.functions){
									for(let child of item.inputs){
										that.$set(child,child.id,'')
									}
								}
								that.functionList = obj.functions
								console.log('functionList',that.functionList)
							}
							console.log(obj)
							if(obj.properties && obj.properties.length > 0){
								that.statusList = obj.properties
								that.properties = obj.properties.map((v) => {return v.id})
							}
						}
						
						that.detail = res.result
						this.getConfig()
					}
				})
			},
			getConfig(){
				const that = this
				const appInstance = getApp();
				_g.apiPost(appInstance.globalData.url + '/api/device-instance/' + that.option.id + '/config-metadata',{},'GET').then(res => {
					if(res.status == 200){
						if(res.result.length > 0){
							res.result.forEach(item => {
								if(item.properties.length > 0){
									item.properties.forEach(child => {
										if(child.type.type === 'password' && !this.isShow){
											that.$set(that.detail.configuration,child.name + 'Val',that.detail.configuration[child.name])
											that.detail.configuration[child.name] = '*'.repeat(that.detail.configuration[child.name].length)
										}
									})
								}
							})
							that.config = res.result
						}
						console.log(res)
						console.log(1233)
						this.getStatus()
					}
				})
			},
			getStatus(){
				const that = this
				const appInstance = getApp();
				let params = [
					{
						dashboard:"device",
						dimension:"history",
						measurement:"properties",
						object:this.detail.productId,
						params:{
							deviceId:this.detail.id,
							history:1,
							properties:this.properties
						}
					}
				]
				console.log(params)
				_g.apiPost(appInstance.globalData.url + '/api/dashboard/_multi',params,'POST').then(res => {
					if(res.status == 200){
						if(res.result && res.result.length > 0){
							this.statusList.forEach(item => {
								let value = res.result.filter(con => con.data.value.property === item.id)
								let formatValue = ''
								let unit = ''
								let time = ''
								if(value.length > 0){
									formatValue = value[0].data.value.value
									unit = value[0].data.value.unit
									time = value[0].data.timeString
								}
								this.$set(item,'formatValue',formatValue)
								this.$set(item,'time',time)
								this.$set(item,'unit',unit)
							})
						}
						console.log(res)
						console.log(this.statusList)
						this.connetWS()
					}
				})
			},
			submit(index){
				const that = this
				const appInstance = getApp();
				let params = {}
				this.functionList[0].inputs.forEach(item => {
					this.$set(params,item.id,item[item.id])
					if(this.selectIndex === 0 && item.valueType.type === 'enum'){
						if(!params[item.id]){
							this.$set(params,item.id,item.valueType.elements[0].value)
						}
					}
				})
				console.log(params)
				this.$refs['baseForm' + index][0].validate().then(res => {
					_g.apiPost(appInstance.globalData.url + '/api/device/invoked/' + this.detail.id + '/function/' + this.functionList[0].id,params,'POST').then(res => {
						console.log(res)
						if(res.status == 200){
							uni.showToast({
							    title: '执行成功',
							    icon: 'success',
							    duration: 2000
							});
						} else {
							uni.showToast({
							    title: res.message,
							    icon: 'error',
							    duration: 2000
							});
						}
					})
				})
			},
			clearForm(data){
				data.inputs.forEach(item => {
					item[item.id] = ''
				})
			},
			connetWS(){
				const appInstance = getApp();
				console.log(appInstance)
				console.log()
				let index = appInstance.globalData.url.indexOf(':')
				let url = ''
				console.log(appInstance.globalData.url.substring(0,index))
				if(appInstance.globalData.url.substring(0,index) === 'http'){
					url = 'ws' + appInstance.globalData.url.substring(index,appInstance.globalData.url.length)
				} else {
					url = 'wss' + appInstance.globalData.url.substring(index,appInstance.globalData.url.length)
				}
				let that = this
				this.ws = uni.connectSocket({url:url + '/api/messaging/' + appInstance.globalData.token});
				console.log(this.ws)
				uni.onSocketOpen((res) => {
					this.socketOpen = true;
					that.sendMessage()
					console.log('WebSocket连接已打开！', res);
				});
				uni.onSocketError((err) => {
					console.error('WebSocket连接打开失败，请检查！', err);
				})
				uni.onSocketMessage((res) => {
					// this.socketMsg = JSON.parse(res.data);
					let data = JSON.parse(res.data).payload
					that.statusList.forEach(item => {
						if(data.properties[item.id] || data.properties[item.id] === 0){
							that.$set(item,'formatValue',data.properties[item.id])
							that.$set(item,'time',moment(data.timestamp).format('YYYY-MM-DD HH:mm:ss'))
						}
					})
					console.log('收到服务器内容：', JSON.parse(res.data));
					console.log(that.statusList)
				});
			},
			closeSocket() {
				if (this.socketOpen) {
					uni.closeSocket();
					this.socketOpen = false;
				}
			},
			// 发送消息
			sendMessage() {
				let that = this
				let sensor = this.detail.productId + '/' + this.detail.id
				if (this.socketOpen){
					uni.sendSocketMessage({
						data:JSON.stringify({
							id: `instance-info-property-${sensor}`,
							topic: `/device/${sensor}/message/property/report`,
							parameter: {
								properties: that.properties, //: ['CO2', 'H2S', 'CH4', 'CO', 'O2', 'Combustible'],
								history: 1
							},
							type: 'sub'
						}),
						success: (res) => {
							console.log('发送数据到服务器成功：', res);
						},
						fail: (err) => {
							console.error('发送数据到服务器失败：', err);
						}
					})
				}
				uni.sendSocketMessage({
					data:JSON.stringify({
						id: `event-${sensor}`,
						topic: `/device/${sensor}/message/event/**`,
						type: 'sub'
					}),
					success: (res) => {
						console.log('发送数据到服务器成功1：', res);
					},
					fail: (err) => {
						console.error('发送数据到服务器失败1：', err);
					}
				})
			}
		},
		onUnload(){
			this.closeSocket()
		}
	}
</script>

<style scoped>
.page-main-head{
	width: 100%;
	height: 220upx;
	background: #fff;
	margin-bottom: 20upx;
	position: relative;
}
.unit-body{
		padding: 20upx;
		display: flex;
		flex-wrap: wrap;
	}
	.unit-body image {
		width: 150upx;
		height: 150upx;
		margin-right: 20upx;
	}
	.unit-body .list-item{
		width: calc(100% - 170upx);
		height: 100%;
	}
	.unit-body .list-item text {
		width: 100%;
		font-size: 32upx;
		line-height: 70upx;
	}
	.unit-body .list-item .list-con{
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}
	.unit-body .list-item .list-tag {
		width: 50%;
	}
	.unit-body .list-item .list-tag text{
		font-size: 24upx;
		line-height: 40upx;
	}
	.unit-body .list-item .list-tag .list-tag-label{
		color: #666;
	}
	.unit-body .list-item .list-tag:last-child{
		width: 100%;
	}
	.list-status{
		width: 120upx;
		height: 50upx;
		position: absolute;
		right: 0;
		top: 20upx;
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: flex-end;
		padding: 0 20upx;
		background-color: #D9DFFD;
		border-radius: 25upx 0 0 25upx;
		box-sizing: border-box;
	}
	.list-status i{
		display: block;
		width: 8upx;
		height: 8upx;
		border-radius: 50%;
		background-color: #092EE7;
	}
	.list-status text{
		font-size: 24upx;
		color: #333;
		margin-left: 10upx;
	}
	.list-status-red{
		background-color: #FAD7DA;
	}
	.list-status-red i{
		background-color: #E60B1C;
	}
.page-detail{
	width: 100%;
	height: calc(100vh - 400upx);
	background: #fff;
}
.page-tabs{
		width: 100%;
		height: 80upx;
		display: flex;
		font-size: 28upx;
		background-color: #f5faf0;
		margin-bottom: 20upx;
	}
	.page-tab{
		width: 25%;
		height: 100%;
		line-height: 80upx;
		text-align: center;
	}
	.page-tab-cur{
		background: #fff;
	}
	.page-tab-con{
		width: 100%;
		height: calc(100% - 100upx);
	}
	.page-info{
		width: 100%;
		padding: 0 20upx;
	}
	.page-info-title{
		width: 100%;
		height: 60upx;
		font-size: 28upx;
		font-weight: bold;
		display: flex;
		align-items: center;
	}
	.page-info-title i{
		display: inline-block;
		width: 6upx;
		height: 50%;
		background: #008700;
		margin-right: 10upx;
	}
	.page-info-item{
		width: 100%;
		font-size: 28upx;
		padding: 10upx 20upx 10upx 0;
		position: relative;
	}
	.page-info-item .page-info-label{
		color: #999;
	}
	.page-info-item /deep/ .uni-icons{
		position: absolute;
		right: 0;
	}
	.page-info-device{
		width: 100%;
		height: auto;
	}
	.page-info-config{
		width: 100%;
		height: auto;
	}
	.page-info-config-title{
		font-size: 24upx;
		padding: 10upx 0;
	}
	.page-status{
		width: 100%;
		padding: 20upx;
	}
	.page-status .page-status-item{
		width: 100%;
		height: auto;
		background: #fff;
		box-shadow: 0 0 20upx rgba(0,0,0,0.2);
		border-radius: 12upx;
		padding: 20upx;
		margin: 0 auto 30upx;
	}
	.page-status .page-status-label{
		font-size: 24upx;
		color: #999;
		line-height: 50upx;
	}
	.page-status .page-status-value{
		font-weight: bold;
		font-size: 32upx;
	}
	.page-status .page-status-time{
		color: #333;
		font-size: 28upx;
	}
	.page-function{
		width: 100%;
		padding: 0 20upx;
	}
	.page-function-item{
		width: 100%;
		height: auto;
		padding: 20upx 0;
		border-bottom: 1px solid #efefef;
	}
	.page-function-item:last-child{
		border:none
	}
	.page-function-item .page-function-label{
		font-size: 28upx;
		color: #999;
		line-height: 60upx;
	}
	.page-function-item .page-function-value{
		color: #333;
		font-size: 28upx;
		line-height: 60upx;
	}
	.page-function-item /deep/ .uni-forms-item__label{
		font-size: 28upx;
		color: #999;
		line-height: 60upx;
	}
	.page-function-btns{
		display: flex;
	}
	.page-function-btns uni-button{
		width: 48%;
		height: 70upx;
		line-height: 70upx;
	}
</style>
